<?php

namespace Admin\Controller;

/**
 * ToWord测试
 */
define ( 'DOCX_PATH', 'Uploads/PaperDocx/' );
class ToWordController extends AdminController {
	function index() {
		if (IS_POST) {
			$Title = I ( 'title' );
			require_once 'ThinkPHP/Library/PHPWord/PHPWord.php';
			$PHPWord = new \PHPWord ();
			
			$properties = $PHPWord->getProperties ();
			$properties->setCreator ( 'ItemBank' );
			$properties->setCompany ( '佳木斯大学' );
			$properties->setTitle ( $Title );
			$properties->setLastModifiedBy ( 'ItemBank' );
			
			// 页面设置
			$sectionStyle = C ( 'APP_SECTION_STYLE' );
			$section = $PHPWord->createSection ( $sectionStyle );
			
			// 试卷头
			$header = $section->createHeader ();
			$header->addWatermark ( C ( 'PAPER_HEADER_PATH' ), array (
					'marginTop' => - 20,
					'marginLeft' => - 5 
			) );
			$footer = $section->createFooter ();
			$footer->addPreserveText ( '第{PAGE}页（共{NUMPAGES}页）', array (
					'name' => '宋体',
					'size' => 9 
			), array (
					'align' => 'right' 
			) );
			$section->addText ( $Title, array (
					'name' => '宋体',
					'bold' => true,
					'size' => 18 
			), array (
					'align' => 'center' 
			) );
			
			$section->addTextBreak ( 5 );
			// Save File
			$objWriter = \PHPWord_IOFactory::createWriter ( $PHPWord, 'Word2007' );
			$DocxFile = iconv ( "utf-8", "GBK", $Title . '(' . time_format ( NOW_TIME, 'YmdHis' ) . ').docx' );
			$ZipFile = iconv ( "utf-8", "GBK", $Title . '(' . time_format ( NOW_TIME, 'YmdHis' ) . ').zip' );
			$objWriter->save ( DOCX_PATH . $DocxFile );
			if (file_exists ( DOCX_PATH . $DocxFile )) {
				$objZip = new \ZipArchive ();
				// Try opening the ZIP file
				if ($objZip->open ( DOCX_PATH . $ZipFile, \ZIPARCHIVE::OVERWRITE ) !== true) {
					if ($objZip->open ( DOCX_PATH . $ZipFile, \ZIPARCHIVE::CREATE ) !== true) {
						throw new Exception ( "Could not open " . $ZipFile . " for writing." );
					}
				}
				$objZip->addFile ( DOCX_PATH . $DocxFile, $DocxFile );
				$objZip->close ();
				
				unlink ( DOCX_PATH . $DocxFile );
				
				$this->success ( '生成文档成功', U ( 'index' ) );
			} else {
				$this->error ( '生成文档失败' );
			}
		}
		$this->display ();
	}
}
?>